<?php
namespace Admin\Controller;
use Think\Log;

/**
 * 订单管理
 * User: linkwhy
 * Date: 2015/10/19
 * Time: 15:09
 */
class OrderController extends AdminController{

    public function index(){
        $show_type = I('get.show_type', 'show');
        $take_count = M('order')->where(array('order_status' => 3))->count();
        if( $take_count > 0 ){
            //有确认收货的状态，那么自动判断该用户是否在规定的收货期限内确认收货
            $this->auto_taketime();
        }
        $order_id = I('get.order_id', '');
        $status = I('get.status', '');
        $start_time = I('get.time-start', 0);
        $end_time = I('get.time-end', 0);
        $class_id = I('get.class_id');
        $where = array();
        unset($_SESSION['down_where']);
        $_SESSION['down_where'] = "o.id > 0";
        if( !empty($status) ){
            $row = explode('|', $status);
            if($row[0] == 'order'){
                if( intval($row[1]) >= 0){
                    $where['order_status'] = $row[1];
                    $_SESSION['down_where'] .= " and order_status = {$row[1]}";
                }


            }else{
                if( (int)$row[1] > 0  ) {
                    $where['return_status'] = $row[1];
                    //$down_where  = array('order_status' => $row[1]);
                    $_SESSION['down_where'] .= " and rg.return_status in(2,3,4,5,6,7,8,9)";
                }
            }
        }
        if( $order_id != '' ){
            $where['o.order_id'] = array('like', '%'.$order_id.'%');

        }
        if ( $start_time != '' ) {
            $where['o.ctime'][] = array('egt',strtotime($start_time));
            $_SESSION['down_where'] .= " and o.ctime >=" . strtotime($start_time);
        }
        if ( $end_time != '' ) {
            $str = 24 * 60 * 60 + strtotime($end_time);
            $where['o.ctime'][] = array('elt', $str);
            $_SESSION['down_where'] .= " and o.ctime <=" . $str;
        }

        if( !IS_ADMIN || !empty($class_id) ){
            if( CLASS_ID == 0 ){
                $where['class_id'] = $class_id;
                $_SESSION['down_where'] .= ' and g.class_id = ' . $class_id;
            }else{
                $where['class_id'] = CLASS_ID;
                $_SESSION['down_where'] .= ' and g.class_id = ' . CLASS_ID;
            }
        }

        if($show_type == 'show'){
            $order = M('order');

            $fields = 'o.id,o.order_id,o.client_id,pock_money,take_status,order_status,o.return_status,o.ctime,wl_order,wl_name,take_id';
            $order->alias('o')->join('__ORDER_ITEM__ item ON item.order_id = o.order_id', 'left')
                ->join('__CART__ c ON item.cart_id = c.id', 'left')
                ->join('__GOODS__ g ON c.goods_id = g.id', 'left');
            $list   = $this->lists($order, $where, 'o.id desc', $fields);
            int_to_string($list);
            //订单已读

            $this->assign('_list', $list);
            $this->meta_title = '订单列表';
            $this->classes = getClassNames();
            $this->display();
        }else{
            $this->downexcel($_SESSION['down_where'], $row[0]);
        }
    }

    public function del(){
        $order_id = I('get.order_id');
        if(M('order')->where(array('order_id' => $order_id))->delete()){
            if(M('order_item')->where(array('order_id' => $order_id))->delete()){
                $this->success('删除成功', U('index'));
            }else{
                $this->error('删除失败');
            }
        }
    }

    /**
     * 修改状态
     */
    public function update_status(){
        $order=  M('order');
        $id = I('get.id');
        $u_data['take_status'] = I('get.take_status', 0);
        $u_data['order_status'] = I('get.order_status', 0);
        $u_data['wl_order'] = I('get.wl_order', '');
        $u_data['wl_name'] = I('get.wl_name', '');
        $rs = $order->where(array('id' => $id))->save($u_data);
        if($rs){
            $this->ajaxReturn(array('status' => true));
        }else{
            $this->ajaxReturn(array('status' => false, 'info' => '操作错误，请稍后再试！'));
        }
    }

    public function detail(){
        $order = M('order_item');
        $list = $order->field('order_id,num,name,price')
            ->join('__CART__ c ON __ORDER_ITEM__.cart_id = c.id')
            ->join('__GOODS__ ON c.goods_id = __GOODS__.id')->where(array('order_id' => I('get.order_id')))->select();
        M('order')->where(array('order_id' => I('get.order_id')))->save(array('is_read' => 1));
        $this->assign('_list', $list);
        $this->display();
    }

    /**
     * 实时获取订单信息
     */
    public function NotReadInfo(){
        $order = M('order');
        $count = $order->where(array('is_read' => 0))->count();
        $this->ajaxReturn(array('count' => $count));
    }

    /**
     * 买家收货地址
     */
    public function bull_address(){
        $client = M('clients_address','caitou_','DB_CONFIG1');
        $row = $client->field(true)->where(array('id' => I('get.take_id')))->find();
        $this->assign('row', $row);
        $this->display();
    }

    //自动结算
    public function auto_taketime(){
        //读取收获期限天数
        $take_time = C('TAKETIME');
        $order = M('order');
        //获取卖家发货时间
        $list_time = $order->field('id,order_id,send_time')->where(array('order_status' => 3))->select();
        //计算收货期限的时间戳
        $temp_time = 60*60*24*intval($take_time);
        $current_time = time();
        foreach($list_time as $key => $val){
            if( $current_time > ($temp_time + intval($val['send_time'])) ){
                //更改订单状态为交易成功
                $order->where( array( 'id' => $val['id'], 'order_id' => $val['order_id'] ) )->save(array('order_status' => 4, 'take_time' => $current_time));
            }
        }
    }

    /**
     * 退货详情
     */
    public function return_index(){
        autoVerifyReturnOrder();    //验证订单
        $rg = M('return_goods');
        $order = M('order');
        $ca = M('clients_address','caitou_','DB_CONFIG1');
        $yorder_id = I('get.order_id');
        $list = $rg->alias('rg')
            ->field('rg.id,rg.order_id,order,return_money,return_time,return_msg,num,name,client_id,return_status,price,picture,class_id')
            ->join('__RETURN_ITEM__ item ON item.order_id = rg.order_id', 'left')
            ->join('__GOODS__ g ON item.goods_id = g.id', 'left')
            ->where(array('order' => $yorder_id))->select();

        //退货信息
        $rgData = $rg->field('order_id,wl_order,wl_name,return_msg,return_status,order,user_msg,return_time')->where(array('order' => $yorder_id))->find();
        //物流信息
        $exp = A('Home/Express');
        $result  = $exp -> getorder( $rgData['wl_order']);
        //原订单信息
//        $ydata = $order->alias('o')->field('pro_id,city_id,area_id,name,phone,address')
//            ->join('__CLIENTS_ADDRESS__ cd ON o.take_id = cd.id')->where(array('order_id' => $yorder_id, 'default' => 1))->find();

        $take_id = $order->where(array('order_id' => $yorder_id))->getField('take_id');
        $ydata = M('clients_address','caitou_','DB_CONFIG1')->field('pro_id,city_id,area_id,name,phone,address')->where(array('id' => $take_id))->find();

        //厂家收货地址
        $cdata = M('clients_address')->field('name,phone,address,code')->where(array('type' => 1, 'class_id' => $list[0]['class_id']))->find();

        $data = array_merge($rgData, $ydata);
        $this->assign('list', $result['data']);
        $this->assign('returnAllMoney', $list[0]['return_money']);
        $this->assign('data', $data);
        $this->assign('cdata', $cdata);
        $this->assign('_list', $list);
        $this->display();
    }

    /**
     * 修改订单状态
     */
    public function update_return_status(){
        $rg = M('return_goods');
        $order = M('order');
        $return_order_id = I('get.order_id');
        $order_id = I('get.order');
        $return_status = I('get.return_status');
        if($return_status == 6){
            $return_money = $rg->where(array('order_id' => $return_order_id))->getField('return_money');
            $shop_id = $order->where(array('order_id' => $order_id))->getField('shop_id');
            $rs = $this->drawbackMoney($order_id, $shop_id, $return_money);
            if( $rs == 1 ){
                $result = $rg->where(array('order_id' => $return_order_id))->save(array('return_status' => 6, 'return_stime' => time()));
                if($result){
                    //退款成功
                    $this->ajaxReturn(array('status' => true));
                }else{
                    $this->ajaxReturn(array('status' => false));
                }
            }else{
                //退款失败
                $this->ajaxReturn(array('status' => false));
            }
        }else{
            if( $rg->where(array('order_id' => $return_order_id))->setField('return_status', $return_status) ){
                $this->success('订单状态更改！', U('return_index', array('order_id' => I('get.order'))));
            }else{
                $this->success('请稍后再试！');
            }
        }
    }

    /**
     * 确认退款
     */
    public function sureReturnMoney(){
        $order = M('order');
        $rg = M('return_goods');
        $order_id = I('post.order');
        $return_order_id = I('post.order_id');
        $return_price = I('post.return_price');
        $shop_id = $order->where(array('order_id' => $order_id))->getField('shop_id');
        $rs = $this->drawbackMoney($order_id, $shop_id, $return_price);
        if( $rs == 1 ){
            $result = $rg->where(array('order_id' => $return_order_id))->save(array('return_status' => 8, 'return_stime' => time()));
            if($result){
                //退款成功
                $this->ajaxReturn(array('status' => true));
            }else{
                $this->ajaxReturn(array('status' => false));
            }
        }else{
            //退款失败
            $this->ajaxReturn(array('status' => false));
        }
    }

    /**
     * 取消退货
     * 作废
     */
    public function cancelReturn(){
        $rg = M('return_goods');
        $order_id = I('get.order');
        $id = I('get.id');
        $result = $rg->where(array('order' => $order_id, 'id' => $id))->setField('return_status', 4);
        if($result){

            $this->success('订单退货已取消！');
        }else{
            $this->error('订单退货取消失败！');
        }
    }

    /**
     * 确认订单
     */
    public function sureReturn(){
        $rg = M('return_goods');
        $order = M('order');
        $order_id = I('get.order');
        $id = I('get.id');
        $result = $rg->where(array('order' => $order_id, 'id' => $id))->save(array('return_status' => 3, 'return_stime' => time()));
        if($result){
            //退货完成
            $row = $rg->alias('rg')->field('order,shop_id,return_money')->join('__ORDER__ o ON rg.order = o.order_id')->where(array('order_id' => $order_id, 'id' => $id))->find();
            $rs = $this->drawbackMoney($row['order'], $row['shop_id'], $row['return_money']);
            if($rs == 1){
                $this->success('订单退款成功！');
            }else{
                $this->error('订单退款失败！');
            }
        }else{
            $this->error('异常操作，请稍后再试！');
        }
    }

    /**
     * 退款操作
     */
    public function drawbackMoney($order_id, $seller_id, $price){
        $arr=array('order_id'=>"$order_id","seller_id"=>"$seller_id","price"=>$price);
        ksort($arr);
        $str="";
        foreach($arr as $k=>$v){
            $str.=$k.$v;
        }
        //echo $str;
        $sign=md5($str."aaa123456");
        $arr['sign']=$sign;

        return apiPost("http://182.92.31.222/server/index.php?c=Order&a=refund",$arr);
    }

    /**
     * 发货详情
     */
    public function send_detail(){
        $order = M('order');
        $item = M('order_item');
        $wuliu = M('wuliu');
        $order_id = I('get.order_id');
        $type = I('get.type');
        $list = $item->alias('item')
            ->field('item.order_id,name,price,picture,num,color,size,foot_width,foot_long,foot_thick,take_text,pock_money')
            ->join('__ORDER__ o ON item.order_id = o.order_id')
            ->join('__CART__ c ON item.cart_id = c.id')
            ->join('__GOODS__ g ON c.goods_id = g.id')
            ->where(array('item.order_id' => $order_id))->select();
        $allprice = $list[0]['pock_money'];
//        foreach($list as $val){
//            $allprice += floatval($val['price']) * intval($val['num']);
//        }

        //获取收货人的地址
//        $data = $order->alias('o')->field('pro_id,city_id,area_id,name,phone,address,wl_name,wl_order')
//                ->join('__CLIENTS_ADDRESS__ cd ON o.take_id = cd.id')->where(array('order_id' => $order_id, 'default' => 1))->find();
        $data1 = $order->field('wl_name,wl_order,take_id,order_status')->where(array('order_id' => $order_id))->find();
        $data2 = M('clients_address','caitou_','DB_CONFIG1')->field('pro_id,city_id,area_id,name,phone,address')->where(array('id' => $data1['take_id']))->find();
        $data = array_merge($data1, $data2);

        $data['allprice'] = number_format($allprice, 2, '.', '');
        $data['order_id'] = $order_id;
        $data['type'] = $type;
        $wulius = $wuliu->field(true)->select();
        $this->assign('_list', $list);
        $this->assign('_wulius', $wulius);
        $this->assign('data', $data);
        $this->display();
    }

    /**
     * 修改收货地址
     */
    public function updateTake(){
        if( M('order')->where(array('order_id' => I('get.order_id')))->setField('take_text', I('get.take_text')) ){
            $this->ajaxReturn(array('status' => true));
        }
    }

    /**
     * 确定发货
     */
    public function sendGoods(){
        $order = M('order');
        $wl_order = I('post.wl_order');
        if( empty($wl_order) ){
            $this->error('物流订单号不能为空！');
            exit;
        }

        $postData = array(
            'order_status' =>3,
            'send_time' => time(),
            'wl_order' => $wl_order,
            'wl_name' => I('post.wl_name')
        );
        $rs = $order->where(array('order_id' => I('post.order_id')))->save($postData);
        if($rs){
            $this->success('发货成功！', U('index'));
        }else{
            $this->error('异常操作！');
        }
    }

    /**
     * 导出
     * @param $where
     */
    public function downexcel($where = array(), $type){
        $xlsName  = "Order-" . date('Y-m-d', time());
        $order = M('order');
        $ca = M('clients_address','caitou_','DB_CONFIG1');

        if($type == 'order'){
            $xlsCell  = array(
                array('key','序号'),
                array('gno', '货号'),
                array('order_id','订单号'),
                array('client_id','用户Id'),
                array('pock_money','交易金额'),
                array('order_status', '订单状态'),
                array('return_status', '退货状态'),
                array('num','数量'),
                array('ctime','订单时间'),
                array('send_time', '发货时间'),
                array('name', '姓名'),
                array('phone', '联系电话'),
                array('wl_name', '物流公司'),
                array('wl_order', '物流订单号'),
                array('take_text', '修改并确认收货地址')
            );

            $list = $order->alias('o')->field('cart.id,gno,o.order_id,o.client_id,pock_money,o.ctime,size,foot_long,foot_width,foot_thick,cart.num,take_id,take_text,order_status,rg.return_status,send_time,o.wl_order,o.wl_name')
                ->join('__ORDER_ITEM__ item ON item.order_id = o.order_id', 'left')
                ->join('__CART__ cart ON item.cart_id = cart.id', 'left')
                ->join('__GOODS_INTRODUCE__ info ON info.gid = cart.goods_id', 'left')
                ->join('__RETURN_GOODS__ rg ON rg.order = o.order_id', 'left')
                ->join('__GOODS__ g ON cart.goods_id = g.id', 'left')->where($where)->select();

            //c.name,phone,address,
            foreach ($list as $k => &$v){
                $row = $ca->field('name,phone,address,pro_id,city_id,area_id')->where(array('id' => $v['take_id']))->find();
                $v['key'] = $k + 1;
                $v['ctime'] = date('Y-m-d H:i:s', $v['ctime']);
                $v['send_time'] = date('Y-m-d H:i:s', $v['send_time']);
                $v['name'] = $row['name'];
                $v['phone'] = $row['phone'];
                $v['detail_address'] = getAreaName($row['pro_id']) . getAreaName($row['city_id']) . getAreaName($row['area_id']) . $row['address'];
                switch($v['order_status']){
                    case 0:
                        $v['order_status'] = '等待买家付款';
                        break;
                    case 1:
                        $v['order_status'] = '等待买家付款';
                        break;
                    case 2:
                        $v['order_status'] = '买家已付款';
                        break;
                    case 3:
                        $v['order_status'] = '卖家已发货';
                        break;
                    case 4:
                        $v['order_status'] = '交易成功';
                        break;
                    case 5:
                        $v['order_status'] = '交易关闭';
                        break;
                    case 6:
                        $v['order_status'] = '交易完成';
                        break;
                }
                if (empty($v['return_status'])) {
                    $v['return_status'] = "";
                } else {

                    switch ($v['return_status']) {
                        case 1:
                            $v['return_status'] = "未退货";
                            break;
                        case 2:
                            $v['return_status'] = "审核中";
                            break;
                        case 3:
                            $v['return_status'] = "审核通过";
                            break;
                        case 4:
                            $v['return_status'] = "审核未通过";
                            break;
                        case 5:
                            $v['return_status'] = "退货中";
                            break;
                        case 6:
                            $v['return_status'] = "确认收货";
                            break;
                        case 7:
                            $v['return_status'] = "退款中";
                            break;
                        case 8:
                            $v['return_status'] = "退款完成";
                            break;
                        case 9:
                            $v['return_status'] = "取消退款";
                            break;
                        case 10:
                            $v['return_status'] = "用户撤销";
                            break;
                    }
                }
                unset($row);
            }
        }else{
            $xlsCell  = array(
                array('key','序号'),
                array('gno', '货号'),
                array('order_id','订单号'),
                array('client_id','用户Id'),
                array('pock_money','交易金额'),
                array('order_status', '订单状态'),
                array('return_status', '退货状态'),
                array('num','数量'),
                array('ctime','订单时间'),
                array('send_time', '发货时间'),
                array('name', '姓名'),
                array('phone', '联系电话'),
                array('wl_name', '物流公司'),
                array('wl_order', '物流订单号'),
                array('open_name','开户名'),
                array('bank_account','开户账号'),
                array('open_bank_name','银行名'),
                array('take_text', '修改并确认收货地址')
            );

            //
            $list = $order->alias('o')->field('cart.id,gno,o.order_id,o.client_id,pock_money,o.ctime,size,cart.foot_long,cart.foot_width,cart.foot_thick,cart.num,take_id,take_text,order_status,rg.return_status,send_time,o.wl_order,o.wl_name')
                ->join('__ORDER_ITEM__ item ON item.order_id = o.order_id', 'left')
                ->join('__CART__ cart ON item.cart_id = cart.id', 'left')
                ->join('__GOODS_INTRODUCE__ info ON info.gid = cart.goods_id', 'left')
                ->join('__RETURN_GOODS__ rg ON rg.order = o.order_id', 'left')
                ->join('__GOODS__ g ON cart.goods_id = g.id', 'left')->where($where)->select();

            //c.name,phone,address,
            $ca2 = M('clients','caitou_','DB_CONFIG1');
            foreach ($list as $k => &$v){
                $row = $ca->field('name,phone,address,pro_id,city_id,area_id')->where(array('id' => $v['take_id']))->find();
                $row1 = $ca2->field('open_bank_name,open_name,bank_account')->where(array('uid' => $v['client_id']))->find();

                $v['key'] = $k + 1;
                $v['ctime'] = date('Y-m-d H:i:s', $v['ctime']);
                $v['send_time'] = date('Y-m-d H:i:s', $v['send_time']);
                $v['name'] = $row['name'];
                $v['phone'] = $row['phone'];
                $v['detail_address'] = getAreaName($row['pro_id']) . getAreaName($row['city_id']) . getAreaName($row['area_id']) . $row['address'];
                $v['open_name'] = $row1['open_name'];
                $v['open_bank_name'] = $row1['open_bank_name'];
                $v['bank_account'] = "'{$row1['bank_account']}'";
                switch($v['order_status']){
                    case 0:
                        $v['order_status'] = '等待买家付款';
                        break;
                    case 1:
                        $v['order_status'] = '等待买家付款';
                        break;
                    case 2:
                        $v['order_status'] = '买家已付款';
                        break;
                    case 3:
                        $v['order_status'] = '卖家已发货';
                        break;
                    case 4:
                        $v['order_status'] = '交易成功';
                        break;
                    case 5:
                        $v['order_status'] = '交易关闭';
                        break;
                    case 6:
                        $v['order_status'] = '交易完成';
                        break;
                }
                if (empty($v['return_status'])) {
                    $v['return_status'] = "";
                } else {

                    switch ($v['return_status']) {
                        case 1:
                            $v['return_status'] = "未退货";
                            break;
                        case 2:
                            $v['return_status'] = "审核中";
                            break;
                        case 3:
                            $v['return_status'] = "审核通过";
                            break;
                        case 4:
                            $v['return_status'] = "审核未通过";
                            break;
                        case 5:
                            $v['return_status'] = "退货中";
                            break;
                        case 6:
                            $v['return_status'] = "确认收货";
                            break;
                        case 7:
                            $v['return_status'] = "退款中";
                            break;
                        case 8:
                            $v['return_status'] = "退款完成";
                            break;
                        case 9:
                            $v['return_status'] = "取消退款";
                            break;
                        case 10:
                            $v['return_status'] = "用户撤销";
                            break;
                    }
                }
                unset($row);
                unset($row1);
            }
        }

        $this->exportExcel($xlsName,$xlsCell,$list);
    }

    /**
     * 修改物流
     */
    public function updateWuliu(){
        $order_id = I('get.order_id');
        $getData = array(
            'wl_order' => I('get.wl_order'),
            'wl_name' => I('get.wl_name')
        );
        if( M('order')->where(array('order_id' => $order_id))->save($getData) ){
            $this->ajaxReturn(array('status' => true));
        }else{
            $this->ajaxReturn(array('status' => false));
        }
    }

    /**
     * 修改状态
     */
    public function updateStatus(){
        $order_id = I('get.order_id');
        $order_status = I('get.order_status');
        if( M('order')->where(array('order_id' => $order_id))->setField('order_status', $order_status) ){
            $this->ajaxReturn(array('status' => true));
        }else{
            $this->ajaxReturn(array('status' => false));
        }
    }

}